const cache = new Map()

const cacheTime = new Map()

export function remoteRequest(prefix, params, remoteFunc, repeatRequest = true, requestTime = 10000) {
  if (params == null) {
    return new Promise((resolve) => {
      resolve([])
    })
  }

  const timeKey = prefix + '#' + JSON.stringify(params)
  let time = ''
  if (repeatRequest) {
    const curTime = new Date().getTime()
    time = cacheTime.get(timeKey)
    if (time == null) {
      cacheTime.set(timeKey, curTime)
      time = curTime
    }

    if (curTime - requestTime >= time) {
      cacheTime.clear()
      cacheTime.set(timeKey, curTime)
      time = curTime
    }
  }

  const key = timeKey + '#' + time

  let item = cache.get(key)
  if (item == null || item.error === true) {
    if (item == null) {
      item = { loading: true, callbacks: [] }
      cache.set(key, item)
    }

    item.loading = true
    item.error = false

    return remoteFunc().then((data) => {
      item.data = data
      for (const callback of item.callbacks) {
        callback(item.data)
      }
      item.loading = false
      item.callbacks = []
      return data
    }).catch(() => {
      item.loading = false
      item.error = true
    })
  } else if (item.loading === true) {
    return new Promise((resolve) => {
      const callback = (data) => {
        resolve(data)
      }
      item.callbacks.push(callback)
    })
  } else {
    return new Promise((resolve) => {
      resolve(item.data)
    })
  }
}